import 'dart:convert';

import 'package:logger/logger.dart';

import '../../service/DataChangeService.dart';
import '../../util/ImSingleton.dart';
import '../dto/base/Resp.dart';
import '../dto/business/SendData.dart';
import 'InitRouter.dart';

class DataChangeRouter {

  final _logger = Logger(printer: PrettyPrinter(),);

  void initCallback(Map<String, CallbackData> callbackMap) {
    callbackMap.putIfAbsent("serverRedirectDataChange", ()=> CallbackData(decodeFunction: DataChangeReq.fromJson, doFunction: dataChange));
  }

  /// 接受服务端消息
  Future<OkResp> dataChange(DataChangeReq changeDataReq) async {
    _logger.i("data change: " + jsonEncode(changeDataReq));
    String userId = ImSingleton.getInstance().session.userId!;

    Object data = await _doBusiness(userId, changeDataReq);
    _logger.i("data change end");
    return OkResp(coder: 20, successDataTime: DateTime.now());
  }

  Object _doBusiness(String userId, DataChangeReq changeDataReq) async {
    DataTypeEnum dataTypeEnum = DataTypeEnum.wrap(changeDataReq.type);

    DataSubTypeEnum dataSubTypeEnum = dataTypeEnum.getDataSubTypeEnum(changeDataReq.subType);
    Object value = dataSubTypeEnum.handler(userId, changeDataReq.key, changeDataReq.value);
    return value;
  }

}